package com.blt.car.home;


import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.blt.car.R;
import com.blt.car.base.BaseTitleBarActivity;
import com.blt.car.base.ViewHolder;

import blt.a3rd.map.DrivingRouteOverlay;
import blt.a3rd.map.OverlayManager;
import blt.a3rd.map.PoiOverlay;


/**
 * Created by xgp on 2017/6/28.
 */
//BaiduMap.OnMapClickListener,
public class MapActivity extends BaseTitleBarActivity implements
        OnGetRoutePlanResultListener, OnGetPoiSearchResultListener {
    public static final String CITY_NAME = "com.blt.car.home.city_name";

    private LinearLayout editLayout;
    private LinearLayout dataLayout;
    private Button startNavigator;
    private EditText etStart;
    private EditText etEnd;
    private TextView tvGenDuration;
    private TextView tvGenAmount;
    private TextView tvGenDistance;
    private TextView tvOtherDuration;
    private TextView tvOtherAmount;
    private TextView tvOtherDistance;


    private PoiSearch mPoiSearch = null;

    // 地图相关，使用继承MapView的MyRouteMapView目的是重写touch事件实现泡泡处理
    // 如果不处理touch事件，则无需继承，直接使用MapView即可
    MapView mMapView = null;    // 地图View
    BaiduMap mBaidumap = null;
    // 搜索相关
    RoutePlanSearch mSearch = null;    // 搜索模块，也可去掉地图模块独立使用
    String startNodeStr;
    String endNodeStr;
    int nodeIndex = -1; // 节点索引,供浏览节点时使用
    DrivingRouteResult nowResultdrive = null;
    private String citystr;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_map;
    }

    @Override
    protected void initData() {
        super.initData();
        citystr = getIntent().getExtras().getString(CITY_NAME);
    }

    @Override
    protected void initView(ViewHolder holder) {
        mTitleBar.setTitle("预估高速费用");
        editLayout = holder.get(R.id.map_location_layout);
        startNavigator = holder.get(R.id.map_confirm_navigator);
        dataLayout = holder.get(R.id.map_data_layout);

        etStart = holder.get(R.id.map_start);
        etEnd = holder.get(R.id.map_end);
        tvGenDuration = holder.get(R.id.map_general_way_duration);
        tvGenAmount = holder.get(R.id.map_general_way_amount);
        tvGenDistance = holder.get(R.id.map_general_way_distance);
        tvOtherDuration = holder.get(R.id.map_other_way_duration);
        tvOtherAmount = holder.get(R.id.map_other_way_amount);
        tvOtherDistance = holder.get(R.id.map_other_way_distance);


        holder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                MapSdk.getMapSdk().start();
                startNodeStr = etStart.getText().toString();
                endNodeStr = etEnd.getText().toString();
                if (TextUtils.isEmpty(startNodeStr)) {
                    toastShort("请输入起点");
                    return;
                }
                if (TextUtils.isEmpty(endNodeStr)) {
                    toastShort("请输入终点");
                    return;
                }
                editLayout.setVisibility(View.GONE);
                startNavigator.setVisibility(View.GONE);
                PlanNode stNode = PlanNode.withCityNameAndPlaceName("深圳", startNodeStr);
                PlanNode enNode = PlanNode.withCityNameAndPlaceName("广州", endNodeStr);
                mSearch.drivingSearch((new DrivingRoutePlanOption())
                        .from(stNode).to(enNode));

            }
        }, R.id.map_confirm_navigator);
        initMap(holder);
    }

    private void initMap(ViewHolder holder) {
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);

        mPoiSearch.searchInCity((new PoiCitySearchOption())
                .city(citystr).keyword("市政府").pageNum(0));


        mMapView = holder.get(R.id.map);
        mBaidumap = mMapView.getMap();
        // 地图点击事件处理
//        mBaidumap.setOnMapClickListener(this);
        // 初始化搜索模块，注册事件监听
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);


    }


//    @Override
//    public void onMapClick(LatLng latLng) {
//
//    }
//
//    @Override
//    public boolean onMapPoiClick(MapPoi mapPoi) {
//        return false;
//    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

    }

    boolean hasShownDialogue = false;
    RouteLine route = null;
    OverlayManager routeOverlay = null;
    boolean useDefaultIcon = false;

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
        }
        dataLayout.setVisibility(View.VISIBLE);
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            // result.getSuggestAddrInfo()
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            nodeIndex = -1;
            if (result.getRouteLines().size() > 1) {//多条路线
                nowResultdrive = result;
                if (!hasShownDialogue) {
                    route = nowResultdrive.getRouteLines().get(0);
                    DrivingRouteLine d1 = result.getRouteLines().get(0);
                    DrivingRouteLine d2 = result.getRouteLines().get(1);

                    int duration1 = d1.getDuration() / 60;//分钟
                    float dis1 = d1.getDistance() / 1000;//km
                    int account1 = (int) (0.45f * d1.getDistance() / 1000);

                    int duration2 = d2.getDuration() / 60;//分钟
                    float dis2 = d2.getDistance() / 1000;//km
                    int account2 = (int) (0.45f * d2.getDistance() / 1000);

                    tvGenDuration.setText(duration1 + "分钟");
                    tvGenAmount.setText("过路费约" + account1 + "元");
                    tvGenDistance.setText(dis1 + "公里");

                    tvOtherDuration.setText(duration2 + "分钟");
                    tvOtherAmount.setText("过路费约" + account2 + "元");
                    tvOtherDistance.setText(dis2 + "公里");

                    DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaidumap);
                    mBaidumap.setOnMarkerClickListener(overlay);
                    routeOverlay = overlay;
                    overlay.setData(nowResultdrive.getRouteLines().get(0));
                    overlay.addToMap();
                    overlay.zoomToSpan();
                }

                hasShownDialogue = true;
            }
        } else if (result.getRouteLines().size() == 1) {//只有1条路线
            route = result.getRouteLines().get(0);
            DrivingRouteLine drivingRouteLine = result.getRouteLines().get(0);

            int duration = drivingRouteLine.getDuration() / 60;//分钟
            float dis = drivingRouteLine.getDistance() / 1000;//km
            int account = (int) (0.45f * drivingRouteLine.getDistance() / 1000);

            tvGenDuration.setText(duration + "分钟");
            tvGenAmount.setText("过路费约" + account + "元");
            tvGenDistance.setText(dis + "公里");

            DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaidumap);
            routeOverlay = overlay;
            mBaidumap.setOnMarkerClickListener(overlay);
            overlay.setData(result.getRouteLines().get(0));
            overlay.addToMap();
            overlay.zoomToSpan();
        } else {
            Log.d("route result", "结果数<0");
            return;
        }

    }

    @Override
    public void onGetPoiResult(PoiResult result) {
        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            toastShort("未找到结果");
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            mBaidumap.clear();
            PoiOverlay overlay = new MyPoiOverlay(mBaidumap);
            mBaidumap.setOnMarkerClickListener(overlay);
            overlay.setData(result);
            overlay.addToMap();
            overlay.zoomToSpan();
        }

    }


    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    private class MyPoiOverlay extends PoiOverlay {

        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int index) {
            super.onPoiClick(index);
            PoiInfo poi = getPoiResult().getAllPoi().get(index);
            // if (poi.hasCaterDetails) {
//            mPoiSearch.searchPoiDetail((new PoiDetailSearchOption())
//                    .poiUid(poi.uid));
            // }
            return true;
        }
    }


    // 定制RouteOverly
    private class MyDrivingRouteOverlay extends DrivingRouteOverlay {

        public MyDrivingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_st);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_en);
            }
            return null;
        }
    }


    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPoiSearch.destroy();

    }
}
